package com.fw.leetcode.tree;

import com.fw.leetcode.LeetCode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 103. Binary Tree Zigzag Level Order Traversal
 *
 * Given the root of a binary tree, return the zigzag level order traversal of its nodes' values.
 * (i.e., from left to right, then right to left for the next level and alternate between).
 *
 * Example 1:
 *  Input: root = [3,9,20,null,null,15,7]
 *  Output: [[3],[20,9],[15,7]]
 *
 * Example 2:
 *  Input: root = [1]
 *  Output: [[1]]
 *
 * Example 3:
 *  Input: root = []
 *  Output: []
 *
 * Constraints:
 *  The number of nodes in the tree is in the range [0, 2000].
 *  -100 <= Node.val <= 100
 */
public class Num_0103 implements LeetCode {
    private interface Solution extends Tree {
        List<List<Integer>> zigzagLevelOrder(TreeNode root);

        default void assertExpected(Integer[] root, int[][] expected) {
            List<List<Integer>> result = zigzagLevelOrder(buildBinaryTree(root));
            for (int i = 0; i < result.size(); i++) {
                for (int j = 0; j < result.get(i).size(); j++) {
                    if (result.get(i).get(j) != expected[i][j]) {
                        zigzagLevelOrder(buildBinaryTree(root));
                    }
                }
            }
        }
    }

    private static class MySolution implements Solution {

        @Override
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) { // 广度优先遍历+双端队列（两头栈）：时O(n) 空O(n)
            /*
             * 二叉树的锯齿形层序遍历（先从左到右，再从右到左，层层遍历）
             *       3              -> 1 get deque.head(left right)  add deque.tail(left right)
             *    9     20          <- 2 get deque.tail(right left)  add deque.head(right left)
             *  -  -  15  7         -> 3 get deque.head(left right)  add deque.tail(left right)
             *       1  2           <- 4 get deque.tail(right left)
             * [[3],[20,9],[15,7]]
             *
             * stack1 top              stack2 tail
             *  |            |              |
             *  -----------------------------
             */
            List<List<Integer>> result = new ArrayList<>();
            ArrayDeque<TreeNode> deque = new ArrayDeque<>();
            if (root == null) {
                return Collections.emptyList();
            }
            deque.push(root);
            int i = 0;
            while (!deque.isEmpty())  {
                int size = deque.size();
                i++;
                List<Integer> layerResult = new ArrayList<>(size);
                if (i % 2 == 1) { // layer
                    while (--size >= 0) {
                        TreeNode node = deque.removeFirst(); // pop stack1
                        layerResult.add(node.val);
                        if (node.left != null) {
                            deque.addLast(node.left); // push stack2
                        }
                        if (node.right != null) {
                            deque.addLast(node.right); // push stack2
                        }
                    }
                } else {
                    while (--size >= 0) {
                        TreeNode node = deque.removeLast(); // pop stack2
                        layerResult.add(node.val);
                        if (node.right != null) {
                            deque.addFirst(node.right); // push stack1
                        }
                        if (node.left != null) {
                            deque.addFirst(node.left); // push stack1
                        }
                    }
                }
                result.add(layerResult);
            }
            return result;
        }
    }

    public static void main(String[] args) {
        Solution solution = new MySolution();
        solution.assertExpected(new Integer[]{3,9,20,null,null,15,7}, new int[][]{{3},{20,9},{15,7}});
        solution.assertExpected(new Integer[]{1}, new int[][]{{1}});
        solution.assertExpected(new Integer[]{}, new int[][]{{}});
    }
}
